import md5 from "js-md5";
import TimeUtil from "../utils/time";
import UserUtil from "../utils/user";
import LogUtil from "../utils/log";
import CommonUtil from "../utils/common";
import Channel from "../utils/channel";

/**
 * 拦截器
 */

let key_ = "8nwBCBVS9KOPAh7EJDXGqCMOdpvwFpHu";
let key = "JaFIJGmuleCsna03IGpgcDn777agTXNm";

export let netWorkInterceptor = {
  request: {
    onFulfilled: (config) => {
      if (config.url.includes("www.syi1.com") ||
        !config.url.startsWith("http")) {
        config.params = CommonUtil.filterNull(config.params)
        let systemInfo = uni.getSystemInfoSync();
        config.params.app = Channel.getAppName()
        config.params.device = systemInfo.platform
        config.params.version = Channel.getAppInfo().versionName
        config.params.user_id = UserUtil.getId()
        if (!config.params.channel) {
          config.params.channel = "web"
        }
        config.params._k = key_
        config.params._t = _t()
        config.params._s = _s(map2params(config.params))

      }
      return config
    },
    onRejected(_) {
      return Promise.reject({code: -999999, msg: '请求异常，请重试~'});
    }
  },
  response: {
    onFulfilled: (response) => {
      if (response.statusCode !== 200) {
        return Promise.reject({
          code: response.statusCode,
          msg: "网络异常，请重试~"
        });
      }
      let result = response.data;
      if (response.config.url.includes("www.syi1.com") ||
        !response.config.url.startsWith("http")) {
        if (result.code !== 200) {
          return Promise.reject({
            code: result.code ?? -999997,
            msg: result.msg ?? "服务器异常，请重试~"
          });
        }
      }
      return Promise.resolve(result.data)
    },
    onRejected: (error) => {
      LogUtil.e(error)
      return Promise.reject({code: -999999, msg: "服务器异常，请重试~"});
    }
  }
}

function _t() {
  return TimeUtil.dateFormat(Date.now());
}

function _s(params) {
  return md5.create().update(params + key).hex()
}

function map2params(map) {
  let keys = Object.keys(map)
  keys.sort()

  let params = ""
  keys.forEach((key, index) => {
    let value = map[key];
    params += key + "=" + value + (index >= keys.length - 1 ? "" : "&");
  })
  return params;
}